package com.monco.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.monco.common.response.ApiResult;
import com.monco.entity.User;
import com.monco.service.IUserService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author com/monco
 * @since 2020-03-11
 */
@Api(tags = "用户模块API")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 修改User方法
     *
     * @param user
     * @return
     */
    @PutMapping
    public ApiResult update(@RequestBody User user) {
        if (StringUtils.isNotBlank(user.getPassword())) {
            String salt = new SecureRandomNumberGenerator().nextBytes().toString();
            String encodedPassword = new SimpleHash("md5", user.getPassword(), salt, 2).toString();
            user.setPassword(encodedPassword);
            user.setSalt(salt);
        }
        userService.updateById(user);
        return ApiResult.ok();
    }

    /**
     * 查询列表
     *
     * @param user
     * @return
     */
    @GetMapping("list")
    public ApiResult list(User user) {
        return ApiResult.ok(userService.getUserList(user));
    }

    /**
     * 查询分页
     *
     * @param current 当前页
     * @param size    一页多少数据
     * @param user
     * @return
     */
    @GetMapping("page")
    public ApiResult page(@RequestParam(required = false, defaultValue = "0") long current,
                          @RequestParam(required = false, defaultValue = "10") long size, User user) {
        return ApiResult.ok(userService.getUserPage(new Page<User>().setCurrent(current).setSize(size), user));
    }

    /**
     * 删除方法
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public ApiResult delete(@RequestParam Long id) {
        userService.removeById(id);
        return ApiResult.ok();
    }

    /**
     * 按照id获取单条记录
     *
     * @param id
     * @return
     */
    @GetMapping
    public ApiResult getOne(@RequestParam Long id) {
        return ApiResult.ok(userService.getById(id));
    }


    /**
     * 获取当前登录用户信息
     */
    @GetMapping("info")
    public ApiResult getUserInfo() {
        Subject subject = SecurityUtils.getSubject();
        User user = userService.getUserList(new User().setUsername(subject.getPrincipal().toString())).get(0);
        return ApiResult.ok(user);
    }
}
